<?php

/*
 * Author: Quan Van Sinh
 * Email: sinhvnb@vietnambiz.com
 * Update: NghiaTruong
 * Email: nghiatruong@vietnambiz.com
 * Date: 16-3-2011
 */

class category {

    function category() {

    }

    function getAllCategory() {
        global $db;
        $sql = "SELECT * FROM article_category ORDER BY cat_order";
        $rsAllCategory = $db->query($sql);
        return $rsAllCategory;
    }

    function get_cat_tree($parent_id = 0, $space = ' ', $trees = NULL) {
        global $db;
        if (!$trees)
            $trees = array();
        $sql = $db->query("SELECT * FROM article_category WHERE  parent_id = " . intval($parent_id) . " ORDER BY cat_order");
        while ($rs = $db->fetch_array($sql)) {
            if ($parent_id == 0) {
                $trees[] = array('id' => $rs['id'], 'name' => $rs['name'], 'cat_menu' => $rs['cat_menu'], 'cat_typical' => $rs['cat_typical'], 'cat_active' => $rs['cat_active']);
            } else {
                $trees[] = array('id' => $rs['id'], 'name' => $space . $rs['name'], 'cat_menu' => $rs['cat_menu'], 'cat_typical' => $rs['cat_typical'], 'cat_active' => $rs['cat_active']);
            }

            $trees = $this->get_cat_tree($rs['id'], $space . '----', $trees);
        }
        return $trees;
    }

    function categoryAction() {
        if (isset($_REQUEST['categoryActionType'])) {
            $actionType = $_REQUEST['categoryActionType'];
            switch ($actionType) {
                case 'addCategory':
                    if (isset($_POST['categoryActionType'])) {
                        $this->addCategory();
                    } else {
                        $this->getAllCategory();
                    }
                    break;
                case 'editCategory':
                    if (isset($_POST['id'])) {
                        $this->editCategory($_POST['id']);
                    } else {
                        $this->getAllCategory();
                    }
                    break;
                case 'updateCategory':
                    if (isset($_POST['edId'])) {
                        $this->updateCategory($_POST['edId']);
                    } else {
                        $this->getAllCategory();
                    }
                    break;
                case 'deleteCategory':
                    if (isset($_POST['id'])) {
                        $this->deleteCategory($_POST['id']);
                    } else {
                        $this->getAllCategory();
                    }
                    break;
                case 'order_up':
                    if (isset($_GET['id'])) {
                        $this->upOrderCategory();
                    } else {
                        $this->getAllCategory();
                    }
                    $this->getAllCategory();
                    break;
                case 'order_down':
                    if (isset($_GET['id'])) {
                        $this->downOrderCategory();
                    } else {
                        $this->getAllCategory();
                    }
                    $this->getAllCategory();
                    break;
                case 'searchArticleRelateBox':
                    $this->getArticleRelateBox();
                    break;
                case 'toggleMenu':
                    if (isset($_POST['id'])) {
                        $this->toggleMenu($_POST['id']);
                    }
                    break;
                case 'toggleTypical':
                    if (isset($_POST['id'])) {
                        $this->toggleTypical($_POST['id']);
                    }
                    break;
                case 'toggleActive':
                    if (isset($_POST['id'])) {
                        $this->toggleActive($_POST['id']);
                    }
                    break;
                default:
                    $this->getAllCategory();
            }
        }
    }

    function getArticleRelateBox() {
        global $db;
        $keyword = filter($_POST['keyword']);
        $dateFrom = filter($_POST['dateFrom']);
        $dateTo = filter($_POST['dateTo']);
        $cat_id = intval($_POST['cat_id']);
        $condition = "";
        if (!empty($keyword)) {
            $condition .= " AND (title LIKE '%$keyword%') ";
        }
        if (!empty($dateFrom)) {
            $condition .= " AND create_date > '$dateFrom' ";
        }
        if (!empty($dateTo)) {
            $condition .= " AND create_date < '$dateTo' ";
        }
        if ($cat_id) {
            $catTree = $this->get_cat_tree($cat_id);
            foreach ($catTree as $k => $rs) {
                $cat_id_string .= $rs['id'] . ',';
            }
            if ($cat_id_string != '') {
                $cat_id_string = substr($cat_id_string, 0, -1);
            } else {
                $cat_id_string = $cat_id;
            }
            $condition .= " AND cat_id IN ($cat_id_string) ";
        }

        $sql = "SELECT id,title FROM article WHERE 1 AND status='yes' $condition ORDER BY create_date DESC LIMIT 50";
        $rs = $db->query($sql);
        $html = "";
        while ($row = $db->fetch_array($rs)) {
            $html .= '<option value="' . $row['id'] . '" title="' . $row['title'] . '">' . $row['title'] . '</option>';
        }
        echo json_encode(array('html' => $html));
        die;
    }

    function addCategory() {
        global $db;
        $categoryname = filter($_POST['categoryname']);
        $parent_id = intval($_POST['parent_id']);
        $link = CleanFileName($categoryname);
        $checkLinkExist = $db->query_first("SELECT id FROM article_category WHERE link='$link'");
        if($checkLinkExist['id']){
            $rsParent = $db->query_first("SELECT link FROM article_category WHERE parent_id=$parent_id");
            $link = $rsParent['link'].'-'.$link;
        }
        $cat_menu = intval($_POST['cat_menu']);
        $cat_typical = intval($_POST['cat_typical']);
        $cat_active = intval($_POST['cat_active']);
        $rsOrder = $db->query_first("SELECT cat_order FROM article_category WHERE parent_id=$parent_id ORDER BY cat_order DESC limit 1");
        $orderPos = intval($rsOrder['cat_order']) + 1;
        $addCategorySql = "INSERT INTO article_category (parent_id,name,link,cat_menu,cat_typical,cat_active,cat_order) VALUES('$parent_id','$categoryname','$link',$cat_menu,$cat_typical,$cat_active,$orderPos)";
        if (empty($categoryname)) {
            $_SESSION['rsMessages'] = "Category name is empty!";
        } else {
            $db->query($addCategorySql);
            $cat_id = $db->mysql_insert_id();
            addEditRelateBox($cat_id, 'category');
            $_SESSION['rsMessages'] = "Add new category successfull!";
        }
    }

    function editCategory($id) {
        global $db;
        $returnData = array();
        $editCategorySql = "SELECT * FROM article_category WHERE id = " . intval($id);
        $editRS = $db->query_first($editCategorySql);
        $editRSRelate = $db->query_first("SELECT * FROM box_relation WHERE art_cat_id=$id AND relate_for='category'");

        $returnData['id'] = $editRS['id'];
        $returnData['parent_id'] = $editRS['parent_id'];
        $returnData['name'] = $editRS['name'];
        $returnData['cat_menu'] = $editRS['cat_menu'];
        $returnData['cat_typical'] = $editRS['cat_typical'];
        $returnData['cat_active'] = $editRS['cat_active'];
        if ($editRSRelate['view_type'] == 'html') {
            $returnData['rbId'] = $editRSRelate['id'];
            $returnData['rbTitle'] = $editRSRelate['box_title'];
            $returnData['rbViewType'] = $editRSRelate['view_type'];
            $returnData['rbValue'] = $editRSRelate['value'];
            $returnData['rbActive'] = $editRSRelate['active'];
        } elseif ($editRSRelate['view_type'] == 'article') {
            $returnData['rbId'] = $editRSRelate['id'];
            $returnData['rbTitle'] = $editRSRelate['box_title'];
            $returnData['rbViewType'] = $editRSRelate['view_type'];
            $returnData['rbActive'] = $editRSRelate['active'];
            if (!empty($editRSRelate['value'])) {
                $rs = $db->query("SELECT id,title FROM article WHERE id IN (" . $editRSRelate['value'] . ")");
                $html = '';
                while ($row = $db->fetch_array($rs)) {
                    $html .= '<option value="' . $row['id'] . '" title="' . $row['title'] . '">' . $row['title'] . '</option>';
                }
                $returnData['rbValue'] = $html;
            }
        }
        echo json_encode($returnData);
        die;
    }

    function updateCategory($id) {
        global $db;
        $categoryname = filter($_POST['edCategoryname']);
        $parent_id = intval($_POST['edParent_id']);
        //$link = CleanFileName($categoryname);
        $cat_menu = intval($_POST['edCatMenu']);
        $cat_typical = intval($_POST['edCatTypical']);
        $cat_active = intval($_POST['edCatActive']);
        $updateCategorySql = "UPDATE article_category SET name='$categoryname',  parent_id='$parent_id',cat_menu=$cat_menu,cat_typical=$cat_typical,cat_active=$cat_active WHERE id = " . intval($id);
        if (empty($categoryname)) {
            $_SESSION['rsMessages'] = "Category name is empty!";
        } else {
            $db->query($updateCategorySql);
            addEditRelateBox(intval($id), 'category');
            $_SESSION['rsMessages'] = "Update category infomations successfull!";
        }
    }

    function deleteCategory($id) {
        global $db;
        $rsCheck = $db->query_first("SELECT * FROM article WHERE cat_id=$id LIMIT 1");
        if (intval($rsCheck['id']) > 0) {
            $_SESSION['rsMessages'] = "Category is not empty, delete false!";
        } else {
            $deleteCategorySql = "DELETE FROM article_category WHERE id = " . intval($id);
            $db->query($deleteCategorySql);
            $_SESSION['rsMessages'] = "Delete category successfull!";
        }
        die;
    }

    // start order
    function upOrderCategory() {
        global $db;
        $id = $_REQUEST['id'];

        $arr_cat_order = $this->getOrder($id);
        $cat_order = $arr_cat_order['cat_order'];
        $cat_parent = $arr_cat_order['parent_id'];
        $arrCatUp = $this->getUpOrder($cat_order, $cat_parent);
        $catUpId = $arrCatUp['id'];
        $catUpOrder = $arrCatUp['cat_order'];
        $data = array();
        $data['cat_order'] = $cat_order;

        $dataUp = array();
        $dataUp['cat_order'] = $catUpOrder;
        if (intval($catUpId > 0)) {

            $db->query("update  article_category set cat_order=$catUpOrder where id=$id");
            $db->query("update  article_category set cat_order=$cat_order where id=$catUpId");
        }
    }

    function getOrder($id) {
        global $db;
        $rsCat = $db->query_first("SELECT cat_order,parent_id FROM  article_category WHERE  id = " . intval($id));
        return $rsCat;
    }

    function getUpOrder($cat_order, $cat_parent) {
        global $db;
        $rsCat = $db->query_first("SELECT id,cat_order FROM  article_category WHERE  cat_order<$cat_order AND parent_id=$cat_parent ORDER BY cat_order DESC");
        return array("id" => $rsCat['id'], "cat_order" => $rsCat['cat_order']);
    }

    function downOrderCategory() {
        global $db;
        $id = intval($_REQUEST['id']);

        $arr_cat_order = $this->getOrder($id);
        $cat_order = $arr_cat_order['cat_order'];
        $cat_parent = $arr_cat_order['parent_id'];
        $arrCatDown = $this->getDownOrder($cat_order, $cat_parent);
        $catDownId = $arrCatDown['id'];
        $catDownOrder = $arrCatDown['cat_order'];
        $data = array();
        $data['cat_order'] = $cat_order;

        $dataUp = array();
        $dataUp['cat_order'] = $catDownOrder;
        if (intval($catDownId) > 0) {
            $db->query("update  article_category set cat_order=$catDownOrder where id=$id");
            $db->query("update  article_category set cat_order=$cat_order where id=$catDownId");
        }
    }

    function getDownOrder($cat_order, $cat_parent) {
        global $db;
        $rsCat = $db->query_first("SELECT id,cat_order FROM  article_category WHERE  cat_order>$cat_order AND parent_id=$cat_parent ORDER BY cat_order ASC");
        return array("id" => $rsCat['id'], "cat_order" => $rsCat['cat_order']);
    }

    //end order

    function toggleMenu($id){
        global $db;
        $rsCat = $db->query_first("SELECT id,cat_menu FROM  article_category WHERE  id = " . intval($id));
        if($rsCat['cat_menu']==1){
            $cat_menu = 0;
        }else{
            $cat_menu = 1;
        }
        $updateCategorySql = "UPDATE article_category SET cat_menu=$cat_menu WHERE id = " . intval($id);
        $db->query($updateCategorySql);        
    }
    function toggleTypical($id){
        global $db;
        $rsCat = $db->query_first("SELECT id,cat_typical FROM  article_category WHERE  id = " . intval($id));
        if($rsCat['cat_typical']==1){
            $cat_typical = 0;
        }else{
            $cat_typical = 1;
        }
        $updateCategorySql = "UPDATE article_category SET cat_typical=$cat_typical WHERE id = " . intval($id);
        $db->query($updateCategorySql);
    }
    function toggleActive($id){
        global $db;
        $rsCat = $db->query_first("SELECT id,cat_active FROM  article_category WHERE  id = " . intval($id));
        if($rsCat['cat_active']==1){
            $cat_active = 0;
        }else{
            $cat_active = 1;
        }
        $updateCategorySql = "UPDATE article_category SET cat_active=$cat_active WHERE id = " . intval($id);
        $db->query($updateCategorySql);
    }
}

?>
